package com.tool.filter;

import com.alibaba.fastjson.JSON;
import com.tool.jwt.JwtUtil;
import com.tool.result.Result;
import org.junit.platform.commons.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2024/1/25 12:21
 * 登录校验过滤器
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.强转为http类型，可以使用http方法
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //2.获取请求url
        String url = req.getRequestURL().toString();
        //3.判断是否为登录页面，即url中是否包含login，是，登录操作，放行
        if (url.contains("login")) {
            chain.doFilter(request, response);
            return;
        }
        //4.获取请求头中的token
        String token = req.getHeader("token");
        //5.判断token令牌是否存在，如果不存在，返回未登录
        if (StringUtils.isBlank(token)) {
            //发送前端信息
            writeResp(resp);
            return;
        }
        //6.解析token，如果解析失败，返回未登录
        try {
            JwtUtil.parseJwt("jwt", token);
        }catch (Exception e) {
            e.printStackTrace();
            //发送前端信息
            writeResp(resp);
            return;
        }
        //7.放行
        chain.doFilter(request, response);
    }

    private void writeResp(HttpServletResponse resp) throws IOException {
        Result error = Result.error("NOT_LOGIN");
        String notLogin = JSON.toJSONString(error);
        resp.getWriter().write(notLogin);
    }
}
